﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using BaseLinQ.DataContex;
using Core;
//using Log = LogFile.Log;

namespace Solution.AppCode
{
    public class UtilsData
    {
        //static Log _logFile = new Log();
        static string strConnectionString = ConfigurationSettings.AppSettings["ConnectString"];
        static RBACDataContext db = new RBACDataContext(strConnectionString);
        public static int _iParent = 0;
        public static int idem = 1;
        public UtilsData()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// Lấy đơn vị thao tác dựa trên miền dữ liệu đc phân
        /// </summary>
        public long LayDonviThaoTac(long _idVaiTro, long _idNguoiDung, string _sMaTaiNguyen, string _sMaThaoTac, string _sTenControl)
        {
            long lngRes = 0;
            DataSet dts = null;
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[5];

                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@in_vaiTroId";
                commandParameter[0].Value = _idVaiTro;

                commandParameter[1] = new SqlParameter();
                commandParameter[1].ParameterName = "@in_nguoiDungId";
                commandParameter[1].Value = _idNguoiDung;

                commandParameter[2] = new SqlParameter();
                commandParameter[2].ParameterName = "@in_maTaiNguyen";
                commandParameter[2].Value = _sMaTaiNguyen;

                commandParameter[3] = new SqlParameter();
                commandParameter[3].ParameterName = "@in_maThaoTac";
                commandParameter[3].Value = _sMaThaoTac;

                commandParameter[4] = new SqlParameter();
                commandParameter[4].ParameterName = "@in_tenControl";
                commandParameter[4].Value = _sTenControl;

                if (commandParameter != null)
                {
                    dts = SqlHelper.ExecuteDataset(strConnectionString, "sp_LayMienDuLieu", commandParameter);
                    if (dts != null)
                    {
                        if (dts.Tables.Count > 0)
                        {
                            if (dts.Tables[0].Rows.Count > 0)
                            {
                                lngRes = long.Parse(dts.Tables[0].Rows[0]["fk_iDonViID"].ToString());
                                dts = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //_logFile.Write("Exception when using Utils.LayDonViThaoTac : " + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
                lngRes = 0;
            }
            return lngRes;
        }

        /// <summary>
        /// Check Quyền thao tác
        /// </summary>
        /// <param name="_iNguoiDungID"></param>
        /// <param name="_iDonViID"></param>
        /// <param name="_iVaiTroID"></param>
        /// <param name="_sTenControl"></param>
        /// <param name="_sMaTaiNguyen"></param>
        /// <param name="_sMaThaoTac"></param>
        /// <returns></returns>
        public bool checkQuyenThaoTac(long _iNguoiDungID, long _iDonViID, long _iVaiTroID, string _sTenControl, string _sMaTaiNguyen, string _sMaThaoTac)
        {
            bool bRes = false;
            DataSet dts = null;
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[6];

                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@in_nguoiDungId";
                commandParameter[0].Value = _iNguoiDungID;

                commandParameter[1] = new SqlParameter();
                commandParameter[1].ParameterName = "@in_donViId";
                commandParameter[1].Value = _iDonViID;

                commandParameter[2] = new SqlParameter();
                commandParameter[2].ParameterName = "@in_vaiTroId";
                commandParameter[2].Value = _iVaiTroID;

                commandParameter[3] = new SqlParameter();
                commandParameter[3].ParameterName = "@in_tenControl";
                commandParameter[3].Value = _sTenControl;

                commandParameter[4] = new SqlParameter();
                commandParameter[4].ParameterName = "@in_maTaiNguyen";
                commandParameter[4].Value = _sMaTaiNguyen;

                commandParameter[5] = new SqlParameter();
                commandParameter[5].ParameterName = "@in_maThaoTac";
                commandParameter[5].Value = _sMaThaoTac;

                if (commandParameter != null)
                {
                    dts =SqlHelper.ExecuteDataset(strConnectionString, "sp_CheckQuyenThaoTac", commandParameter);
                    if (dts != null)
                    {
                        if (dts.Tables.Count > 0)
                        {
                            if (dts.Tables[0].Rows.Count > 0)
                            {
                                bRes = bool.Parse(dts.Tables[0].Rows[0]["ketQua"].ToString());
                                dts = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //_logFile.Write("Exception when using Utils.CheckQuyenThaoTac : " + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
                bRes = false;
            }
            return bRes;
        }

        public static  tbl_NguoiDung GetUserInfo()
        {
            tbl_NguoiDung objUser = new tbl_NguoiDung();
            db = new RBACDataContext(strConnectionString);
            try
            {
                if (HttpContext.Current.Session[Constants.session_user_id] != null)
                {
                    string strUserID = HttpContext.Current.Session[Constants.session_user_id].ToString();
                    objUser = (from m in db.tbl_NguoiDungs
                               where m.pk_iNguoiDungID == long.Parse(strUserID)
                               && m.bKichHoat == true
                               select m).FirstOrDefault<tbl_NguoiDung>();
                }
            }
            catch (Exception ex)
            {
                //_logFile.Write("Exception when using Utils.GetUserInfo : " + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
            }
            return objUser;
        }

        /// <summary>
        /// Lấy ID đơn vị của người dùng đăng nhập
        /// </summary>
        /// <returns></returns>
        public static long GetUserDepartment()
        {
            long lngRes = 0;
            if (HttpContext.Current.Session[Constants.session_user_id] != null)
            {
                lngRes = long.Parse(HttpContext.Current.Session[Constants.session_user_department].ToString());
            }
            return lngRes;
        }

        /// <summary>
        /// Lấy tên đăng nhập của người dùng
        /// </summary>
        /// <returns></returns>
        public string GetUserName()
        {
            string strRes = "";
            if (HttpContext.Current.Session[Constants.session_user_id] != null)
            {
                strRes = HttpContext.Current.Session[Constants.session_user_name].ToString();
            }
            return strRes;
        }

        public string GetFullName()
        {
            string strRes = "";
            if (HttpContext.Current.Session[Constants.session_user_id] != null)
            {
                strRes = HttpContext.Current.Session[Constants.session_full_name].ToString();
            }
            return strRes;
        }

        /// <summary>
        /// Lấy ID của đơn vị gốc theo ID đơn vị truyền vào
        /// </summary>
        /// <param name="_DepartmentID"></param>
        /// <returns></returns>
        public static long GetRootDepartmentID(long _DepartmentID)
        {
            long lngRes = 0;
            using (SqlConnection conn = new SqlConnection(strConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT dbo.f_LayDonViRootID(" + _DepartmentID + ")", conn))
                {
                    conn.Open();
                    lngRes = (long)cmd.ExecuteScalar();
                    conn.Close();
                }
            }
            return lngRes;
        }

        public static int GetUserId()
        {
            int lngRes = 0;
            if (HttpContext.Current.Session[Constants.session_user_id] != null)
            {
                lngRes = int.Parse(HttpContext.Current.Session[Constants.session_user_id].ToString());
            }
            return lngRes;
        }

       //public string GetDepartment()
       // {
       //     _iParent = 0;
       //     idem = 1;
       //     tbl_NguoiDung objUser = GetUserInfo();
       //     if (objUser != null)
       //     {
       //         DonViLogic objLogic = new DonViLogic();
       //         DataSet _dset = new DataSet();
       //         string _keyWork = "";

       //         _dset = objLogic.GetDonVi(_keyWork);
       //         if (_dset != null)
       //         {
       //             if (_dset.Tables.Count > 0)
       //             {
       //                 DataTable dtbReportData = new DataTable();
       //                 DataTable dtbTop = new DataTable("Modul");
       //                 DataTable dtbAllChild = _dset.Tables[0];
       //                 dtbTop = objLogic.GetDonVi("0-1").Tables[0];
       //                 if (dtbAllChild.Rows.Count > 0)
       //                 {
       //                     if (dtbTop != null)
       //                     {
       //                         if (dtbTop.Rows.Count > 0)
       //                         {
       //                             dtbTop.Clear();
       //                         }
       //                     }
       //                     string iDonviID = "0";
       //                     if (HttpContext.Current.Session[Constants.session_donviquanly_id] != null)
       //                     {
       //                         iDonviID = HttpContext.Current.Session[Constants.session_donviquanly_id].ToString();
       //                     }
       //                     DataRow[] dr = dtbAllChild.Select("pk_iDonViID= " + iDonviID);

       //                     int iLever = 0;
       //                     dtbReportData = dtbTop.Clone();
       //                     foreach (DataRow drowData in dr)
       //                     {
       //                         BuildData(dtbReportData, dtbAllChild, drowData, 0, 0, 0);

       //                         iLever++;
       //                     }
       //                     // add number list
       //                     dtbReportData = AddNumberedListToDataTable(dtbReportData, "sTenDonVi");
       //                     foreach (DataRow dr1 in dtbReportData.Rows)
       //                     {
       //                         string _khoangchang = "";
       //                         for (int i = 0; i < TypeHelper.ToInt32(dr1["Level1"].ToString()) + 1; i++)
       //                         {
       //                             _khoangchang += HttpUtility.HtmlDecode("&nbsp;&nbsp;&nbsp;&nbsp;");
       //                         }
       //                         dr1["sTenDonVi"] = _khoangchang + dr1["NumberedList"] + dr1["sTenDonVi"];
       //                     }
       //                     string _arrId = "";
       //                     string _phay = "";
       //                     if (dtbReportData != null)
       //                     {
       //                         foreach (DataRow _dr in dtbReportData.Rows)
       //                         {
       //                             _arrId = _arrId + _phay + _dr["pk_iDonViID"].ToString();
       //                             _phay = ",";
       //                         }
       //                         return _arrId;
       //                     }

       //                 }
       //             }
       //         }
       //     }
       //     return "";
       // }
        /// <summary>
        /// Lấy ra đơn vị quản lý
        /// </summary>
        /// <returns></returns>
        public static string LayDonViQuanLy()
        {
            return HttpContext.Current.Session[Constants.session_donviquanly_id].ToString();
        }

        /// <summary>
        /// Lay id cua menu duoc request theo URL
        /// </summary>
        /// <param name="url">url truyen vao</param>
        /// <returns></returns>
        public static string getRequestMenuId(string url)
        {
            string[] parts = url.Split('/');
            try
            {
                for (int i = 0; i < parts.Count(); i++)
                {
                    if (parts[i] == "Admin")
                    {
                        return parts[i + 1];
                    }
                }
            }
            catch (Exception ex)
            {
                //_logFile.Write("Exception when using Utils.getReQuestMenuID :" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
            }
            return "";
        }

        /// <summary>
        /// Chèn thêm css để hover 
        /// </summary>
        /// <param name="htmlCode"></param>
        /// <param name="requestMenu"></param>
        /// <param name="insertString"></param>
        /// <returns></returns>
        public static string setHoverMenu(string htmlCode, string requestMenu, string insertString)
        {
            if (htmlCode.Contains(requestMenu))
            {
                htmlCode = htmlCode.Replace(insertString, "");
                int index = htmlCode.IndexOf(" href='" + requestMenu);
                return htmlCode.Insert(index, insertString);
            }
            return htmlCode;
        }
        /// <summary>
        /// Lấy sesstion, check timeout
        /// </summary>
        /// <param name="response"></param>
        /// <param name="page"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetSession_value(HttpResponse response, Page page, string request)
        {
            if (HttpContext.Current.Session[request] != null)
            {
                return HttpContext.Current.Session[request].ToString();
            }
            response.Redirect(page.ResolveUrl("~/") + "Admin/Login/Default.aspx");
            return "";
        }

        /// <summary>
        /// lấy kì chấm công theo ID
        /// </summary>
        /// <param name="_lngKyChamCong"></param>
        /// <returns></returns>
        //public static tbl_KyChamCong SelectKyChamCongByID(long _lngKyChamCong)
        //{
        //    IVT12CDataContext db = new IVT12CDataContext(strConnectionString);
        //    tbl_KyChamCong objRes = (from m in db.tbl_KyChamCongs
        //                             where m.pk_iKyChamCongId == _lngKyChamCong
        //                             select m).FirstOrDefault<tbl_KyChamCong>();
        //    return objRes;
        //}
        #region Build Data
        public void BuildData(DataTable pdtbData, DataTable pdtbAllChild, DataRow pdrowNew, int pintLevel, int pintCCNID, int pintCategoryID)
        {
            try
            {
                DataRow drowItem = pdtbData.NewRow();
                foreach (DataColumn dcolData in pdtbData.Columns)
                    drowItem[dcolData.ColumnName] = pdrowNew[dcolData.ColumnName];
                drowItem["Level1"] = pintLevel;
                pdtbData.Rows.Add(drowItem);
                DataRow[] drowsChild = GetChild(pdtbAllChild, int.Parse(drowItem["pk_iDonViID"].ToString()));
                foreach (DataRow drowChild in drowsChild)
                    BuildData(pdtbData, pdtbAllChild, drowChild, pintLevel + 1, pintCCNID, pintCategoryID);
            }
            catch (Exception ex)
            {
                //_logFile.Write("Exception when using Utils.BuildData :" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
            }
        }
        private DataRow[] GetChild(DataTable pdtbAllChilds, int pintParentID)
        {
            try
            {
                DataRow[] drowResult = pdtbAllChilds.Select("iParent_ID = '" + pintParentID.ToString() + "'");
                return drowResult;
            }
            catch (Exception ex)
            {
                //_logFile.Write("Exception when using Utils.GetChild :" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
                DataRow[] drowResult = pdtbAllChilds.Select("iParent_ID = '" + pintParentID.ToString() + "'");
                return drowResult;
            }
        }

        public DataTable AddNumberedListToDataTable(DataTable pdtb, string _fieldName)
        {
            try
            {
                _iParent = 0;
                DataTable dtbRet = pdtb.Copy();

                DataColumn odcol = new DataColumn("NumberedList");
                odcol.DataType = typeof(string);
                odcol.DefaultValue = "";
                dtbRet.Columns.Add(odcol);

                int[] arriInputLevel = ExtractArrayOfLevelFromDataTable(pdtb);
                StringCollection arrNumberedList = GetNumberedList(arriInputLevel, 0, ".");

                int intCount = 0;
                foreach (DataRow row in dtbRet.Rows)
                {
                    string strNumber = arrNumberedList[intCount];
                    string strPartNo = row[_fieldName].ToString();
                    row["NumberedList"] = strNumber;
                    // indent the part no following the level
                    int intLevel = int.Parse(row["Level1"].ToString());
                    intCount++;
                }
                return dtbRet;
            }
            catch (Exception ex)
            {
                //_logFile.Write("Exception when using Utils.AddNumberedListToDataTable :" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
                return null;
            }
        }

        public static int[] ExtractArrayOfLevelFromDataTable(DataTable pdtb)
        {
            try
            {
                int[] arrintRet = new int[pdtb.Rows.Count];
                int intCount = 0;
                foreach (DataRow row in pdtb.Rows)
                {
                    arrintRet[intCount] = int.Parse(row["Level1"].ToString());
                    intCount++;
                }
                return arrintRet;
            }
            catch (Exception ex)
            {
                //_logFile.Write("Exception when using Utils.ExtractArrayOfLevelFromDataTable :" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
                return null;
            }
        }

        public static StringCollection GetNumberedList(int[] parriInput, int pintRootNumber, string pstrDeli)
        {
            try
            {
                #region DEFINE Variables

                StringCollection arrRet = new StringCollection();
                int intRecordCount = parriInput.Length;
                StringCollection arrParentString = new StringCollection();
                for (int intCounter = 0; intCounter < intRecordCount + 1; intCounter++)
                {
                    arrParentString.Add("");
                }
                int[] arriLevelHit = new int[intRecordCount + 1];

                #endregion

                int intPrev = pintRootNumber; // in start phase, iRootNumber is iPrev
                foreach (int i in parriInput)
                {
                    string strOut = "";
                    /// Update level hit count == active running number of last index
                    (arriLevelHit[i])++; // increase the hit count  of level i
                    arriLevelHit[i + 1] = 0; // reset hit count of level i+1 to ZERO

                    if (i == pintRootNumber) // if the level is restart to iRootNumber
                    {
                        // level 0, not exist
                        // Parent string of level iRootNumber, alway = ""
                        // strOut always = "1"
                        arrParentString[i] = "";
                        strOut = idem.ToString();
                        // strOut = "1";
                        idem++;
                    }
                    else
                    {
                        strOut = arrParentString[i] + pstrDeli + arriLevelHit[i];
                        if (strOut.StartsWith("."))
                            strOut = strOut.Remove(0, 1);
                    }
                    intPrev = i;
                    arrParentString[i + 1] = strOut;
                    arrRet.Add(strOut);
                }
                return arrRet;
            }
            catch (Exception ex)
            {
                //_logFile.Write("Exception when using Utils.GetNumberedList :" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
                return null;
            }
        }
        #endregion
    }
}